//
//  UILabel+BRFont.m
//  template
//
//  Created by SoXun on 2018/7/13.
//  Copyright © 2018年 soxun. All rights reserved.
//

#import "UILabel+BRFont.h"
#import <objc/runtime.h>

@implementation UILabel (BRFont)

static const void *Key = "isAdaptiveFont";
static float FontSize = 1;
+(void)load{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSUserDefaults * ll = [NSUserDefaults standardUserDefaults];
         NSString * hh =   [ll stringForKey:@"fontSize"];
        if (hh) {
            FontSize = [hh floatValue];
        }else{
            if (HM_ISiPHONE5ORSE) {
                FontSize = 0.9;
            }else if (HM_ISiPHONE4){
                FontSize = 0.8;
            }
        }
        Method m2 = class_getInstanceMethod([self class], @selector(setFont:));
        Method m1 = class_getInstanceMethod([self class], NSSelectorFromString(@"br_setFont:"));
        method_exchangeImplementations(m2, m1);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeFont:) name:ChangeFontNotificationCenterName object:nil];
        
        
        Method m3 = class_getInstanceMethod([self class], @selector(awakeFromNib));
        Method m4 = class_getInstanceMethod([self class], NSSelectorFromString(@"YHBaseAwakeFromNib"));
        method_exchangeImplementations(m3, m4);
        
      });
}


-(void)YHBaseAwakeFromNib{
    
    if (![self isKindOfClass:[UILabel class]]) {
        return;
    }
    UIFont * font = [UIFont systemFontOfSize:self.font.pointSize];
    
    if (font) {
        
        self.font=font;
        
    }
    [self YHBaseAwakeFromNib];
   
}

- (void)br_setFont:(UIFont *)font{
    if ([self.isAdaptiveFont isEqualToString:@"不改变"]) {
         [self br_setFont:font];
        return;
    }
//    if (self.isAdaptiveFont) {
        font = [UIFont systemFontOfSize:font.pointSize * FontSize];
//    }
  [self br_setFont:font];
}
+ (void)ChangeFont:(NSNotification *)tion{
    FontSize = [tion.object floatValue];
}
- (void)setIsAdaptiveFont:(NSString *)isAdaptiveFont{
objc_setAssociatedObject(self, &Key, isAdaptiveFont, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)isAdaptiveFont{
     return objc_getAssociatedObject(self, &Key);
}


+(UIFont *)AdaptiveFont:(CGFloat)fontSize{
  
        return LBFont(fontSize);
}
- (void)AdaptiveWithSize:(CGFloat)fontSize{
    self.isAdaptiveFont = @"";
    self.font = LBFont(fontSize);
}
@end
